package com.web.util.rsaUtil;

import org.apache.tomcat.util.codec.binary.Base64;

import java.security.KeyFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;


public class RSAEncrypt {

	public static void main(String[] args) throws Exception {

		String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCowwu8ftM+/PPlG5sNFjFtiNG4zsMCRTmfQuMXK6B6YV9Fs1k9a6z6sUVOsqvC2f3QecaOt2obNs8UdPw/EleOcYk/8Z7asVVJcARcYHiQ8NkBUmPyUQKAFiKjVvhtHpCfWZDfurHEQI/rE2mGCB9nMNJcvaSMjK/U0uyEMweqawIDAQAB";
		// 公钥
		String RSA_AREA_PRIVATEKEY_CS1 = "MIICXQIBAAKBgQCowwu8ftM+/PPlG5sNFjFtiNG4zsMCRTmfQuMXK6B6YV9Fs1k9a6z6sUVOsqvC2f3QecaOt2obNs8UdPw/EleOcYk/8Z7asVVJcARcYHiQ8NkBUmPyUQKAFiKjVvhtHpCfWZDfurHEQI/rE2mGCB9nMNJcvaSMjK/U0uyEMweqawIDAQABAoGBAJhmYv/bDAuSxPG+Bzw/MW24I6Qf28z+FLY04fy3ohlCO5YnC0zDIxfU5EDYavHwiBwvDFcvXTusOD9CEdUnTDbX8eu+G9x+lo0qQl0/QeBlas7+sYgIda9MA6BO5ibS4gCORJD8WZviBIpug/PZlZ/P2lI5KpEO2S8ALtrrzhypAkEA0ptqyT96N9aQqRBjdryTINwstkecKBlHo5p51TOqLfPrqdC+M+UPQJkWhF7dUxsmrXkreOP8hjRCLEYj2MvdFQJBAM0iwMM1OvGsCZjMA85yuOEDHSAxpCMHizSXEQ+Ujv53uIIkJmJw0E3weEOPECImCqdEcCSUXOz03MW1Re7ySX8CQFkaNeik+YFMPvG4JEyk5Z5eaHBKBbAVWfDGt0rTS+mbLBYxYXc1LunGmvcv53V0pD16aUEBO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f1U3s=";

		// 接收数据 公钥加密-私钥解密
		String test = "aaa000";
		String miwen = encrypt(test, publicKey);
		System.out.println(test + "\t加密后的字符串为:" + miwen);
		System.out.println("还原后的字符串为:" + decrypt(miwen, RSA_AREA_PRIVATEKEY_CS8));
	}

	public static String encrypt(String str, String publicKey) throws Exception {
		// base64编码的公钥
		byte[] decoded = Base64.decodeBase64(publicKey);
		RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA")
				.generatePublic(new X509EncodedKeySpec(decoded));
		// RSA加密
		Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.ENCRYPT_MODE, pubKey);
		String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
		return outStr;
	}

	public static String decrypt(String str, String privateKey) throws Exception {
		// 64位解码加密后的字符串
		byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
		// base64编码的私钥
		byte[] decoded = Base64.decodeBase64(privateKey);
		RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA")
				.generatePrivate(new PKCS8EncodedKeySpec(decoded));
		// RSA解密
		Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.DECRYPT_MODE, priKey);
		String outStr = new String(cipher.doFinal(inputByte));
		return outStr;
	}

}
